import React, { useState, useEffect, useMemo, useCallback } from 'react'
import { DollarSign, ShoppingCart, Users, Package, TrendingUp, Target, AlertCircle, Percent, Maximize2 } from 'lucide-react'
import { StatsCard, TrendChart, DataTable, PieChartCard, AnimatedLineChart, AnimatedBarChart, AnimatedPieChart, DataComparison } from './components'
import FullscreenMode from './components/FullscreenMode'
import { EnhancedMetricCard, OrderDetailModal, StoreDetailModal, StoreListModal, MoreDataModal } from './components/enhanced'
import { dashboardAPI, type RealTimeData, type SalesTrendItem, type CategorySalesItem, type SalesPieItem, type DataComparisonItem, type BusinessModuleDataResponse } from '../../utils/api'

// 订单数据类型
interface ProductInfo {
  _id: string;
  shopname: string;
  price: number;
  nums: number;
  store: string;
}

interface OrderData {
  _id: string;
  studentId: ProductInfo;
  quantity: number;
  totalPrice: string;
  customerName: string;
  customerPhone: string;
  address: string;
  status: '待处理' | '已发货' | '已完成' | '已取消';
  createdAt: string;
}

// 商品类型和商品数据接口
interface ProductData {
  _id: string;
  shopname: string;
  store: string;
  pass: string;
  price: string;
  nums: number;
  tid: string; // 商品类型ID
}


// 解析订单价格（支持字符串和数字）- 移到组件外部以避免依赖项变化
const parsePrice = (price: string | number): number => {
  if (typeof price === 'number') return price;
  if (typeof price === 'string') {
    const cleanPrice = price.replace(/[¥\s,]/g, '').trim();
    return parseFloat(cleanPrice) || 0;
  }
  return 0;
};

// 生成模拟订单数据的辅助函数（移到组件外部以避免初始化顺序问题）
const generateMockOrders = (): OrderData[] => {
  const statusOptions = ['待处理', '已发货', '已完成', '已取消'];
  const products = ['iPhone 15 Pro', 'MacBook Air', 'iPad Pro', 'AirPods Pro', 'Apple Watch', 'MacBook Pro', 'AirPods Max', 'iPad Air'];
  const stores = ['北京旗舰店', '上海旗舰店', '广州旗舰店', '深圳旗舰店', '杭州旗舰店'];
  const customers = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'];
  const regions = ['北京市朝阳区', '上海市浦东新区', '广州市天河区', '深圳市南山区', '杭州市西湖区', '南京市秦淮区', '武汉市江汉区', '成都市锦江区'];

  return Array.from({ length: 30 }, (_, i) => {
    const randomProductIndex = Math.floor(Math.random() * products.length);
    const randomPrice = Math.floor(Math.random() * 15000) + 800;
    const randomQuantity = Math.floor(Math.random() * 5) + 1;

    return {
      _id: `ORD${String(Date.now() + i).slice(-8)}`,
      studentId: {
        _id: `PROD${String(i + 1).padStart(6, '0')}`,
        shopname: products[randomProductIndex],
        price: randomPrice,
        nums: Math.floor(Math.random() * 200) + 50,
        store: stores[Math.floor(Math.random() * stores.length)]
      },
      quantity: randomQuantity,
      totalPrice: (randomPrice * randomQuantity).toString(),
      customerName: customers[Math.floor(Math.random() * customers.length)],
      customerPhone: `138${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`,
      address: regions[Math.floor(Math.random() * regions.length)] + 'XX街道XX号',
      status: statusOptions[Math.floor(Math.random() * statusOptions.length)] as '待处理' | '已发货' | '已完成' | '已取消',
      createdAt: new Date(Date.now() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000)).toISOString()
    };
  });
};

const Dashboard: React.FC = () => {
  // 大屏模式状态
  const [isFullscreen, setIsFullscreen] = useState(false)
  
  // 订单明细弹窗状态
  const [showOrderDetail, setShowOrderDetail] = useState(false)
  
  // 门店详情弹窗状态
  const [showStoreDetail, setShowStoreDetail] = useState(false)
  const [selectedStore, setSelectedStore] = useState<{ rank: number; name: string; visitors: string; rate: string } | null>(null)
  
  // 全部门店列表弹窗状态
  const [showStoreList, setShowStoreList] = useState(false)
  
  // 更多数据弹窗状态
  const [showMoreData, setShowMoreData] = useState(false)
  
  // 数据加载状态
  const [loading, setLoading] = useState(true)
  
  // 实时数据状态
  const [realTimeData, setRealTimeData] = useState<RealTimeData>({
    sales: 0,
    orders: 0,
    users: 1234,
    products: 0, // 将从商品管理API获取
    conversionRate: 3.8,
    avgOrderValue: 0,
    stockAlerts: 23,
    returnRate: 2.3,
    salesTrend: 15.8,
    ordersTrend: 8.2
  })

  // 数据同步状态
  const [lastSyncTime, setLastSyncTime] = useState<string>('')
  
  // 销售趋势数据
  const [salesTrendData] = useState<SalesTrendItem[]>([])
  
  // 类别销售数据
  const [categorySalesData] = useState<CategorySalesItem[]>([])
  
  // 销售占比数据（饼图）
  const [salesPieData] = useState<SalesPieItem[]>([])
  
  // 新增：所有订单数据（与订单管理页面关联）
  const [allOrders, setAllOrders] = useState<OrderData[]>([])

  // 新增：日期筛选状态
  const [filteredDate, setFilteredDate] = useState('')

  // 新增：选中的订单类型
  const [selectedOrderType, setSelectedOrderType] = useState<string>('all')
  const [orderDetailTitle, setOrderDetailTitle] = useState<string>('全部订单明细')
  
  // 数据对比分析数据
  const [comparisonData, setComparisonData] = useState<DataComparisonItem[]>([])
  
  // 业务模块数据
  const [businessModuleData, setBusinessModuleData] = useState<BusinessModuleDataResponse | null>(null)

  // 商品数据状态
  const [products, setProducts] = useState<ProductData[]>([])

  // 预留：按门店查看详细趋势的回调（如需使用可从 allOrders 中按门店聚合统计）

  // 从订单数据计算实时销售数据 - 确保与订单管理页面完全一致
  // parsePrice 已移到组件外部，无需作为依赖项
  const calculateRealTimeDataFromOrders = useCallback((orders: OrderData[]) => {
    // 计算今日销售额和订单数
    const today = new Date().toISOString().split('T')[0];
    let todaySales = 0;
    let todayOrders = 0;
    let totalAmount = 0;

    // 统计所有订单的总销售额
    orders.forEach((order: OrderData) => {
      try {
        const price = parsePrice(order.totalPrice);
        totalAmount += price;

        // 检查是否为今日订单
        if (order.createdAt) {
          const orderDate = new Date(order.createdAt).toISOString().split('T')[0];
          if (orderDate === today) {
            todaySales += price;
            todayOrders += 1;
          }
        }
      } catch (e) {
        console.warn('[数据看板] 处理订单数据失败:', order._id, e);
      }
    });

    // 计算客单价
    const avgOrderValue = orders.length > 0 ? Math.round(totalAmount / orders.length) : 0;

    // 设置默认趋势值
    const salesTrend = 15.8;
    const ordersTrend = 8.2;

    return {
      sales: todaySales,
      orders: todayOrders,
      avgOrderValue,
      salesTrend,
      ordersTrend
    };
  }, []); // parsePrice 已移到组件外部，无需依赖

  // 获取订单数据（与订单管理页面统一使用相同API端点）
  const fetchOrdersData = useCallback(async () => {
    try {
      console.log('[数据看板] 开始获取订单数据...')
      // 统一使用订单管理页面的API端点
      const ordersRes = await fetch('http://localhost:3000/hsl/order/list', {
        cache: 'no-cache',
        headers: {
          'Cache-Control': 'no-cache',
          'Pragma': 'no-cache'
        }
      })
      const ordersData = await ordersRes.json()

      if (ordersData.code === 200 && Array.isArray(ordersData.data)) {
        const orders = ordersData.data || [];
        setAllOrders(orders);
        console.log('[数据看板] 成功设置订单数据:', orders.length, '条')

        // 从订单数据计算并更新实时数据
        const realTimeStats = calculateRealTimeDataFromOrders(orders);
        setRealTimeData(prev => ({ ...prev, ...realTimeStats }));

        // 更新同步时间
        setLastSyncTime(new Date().toLocaleTimeString('zh-CN'));

        return orders;
      } else {
        console.warn('[数据看板] API返回格式不符，使用模拟数据')
        // 如果API返回格式不符，使用模拟数据
        const mockOrders = generateMockOrders();
        setAllOrders(mockOrders);
        return mockOrders;
      }
      } catch (err) {
      console.error('[数据看板] 获取订单列表失败:', err)
      // 生成模拟订单列表数据
      const mockOrders = generateMockOrders();
      setAllOrders(mockOrders);
      return mockOrders;
    }
  }, [calculateRealTimeDataFromOrders]);
  
  // 获取商品数据
  const fetchProducts = useCallback(async () => {
    try {
      console.log('[数据看板] 开始获取商品数据...')
      const response = await fetch('http://localhost:3000/hsl/product/list', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      const data = await response.json();
      
      if (data.code === 200 && Array.isArray(data.data)) {
        setProducts(data.data);
        console.log('[数据看板] 成功获取商品数据:', data.data.length, '件商品')
      }
    } catch (error) {
      console.error('[数据看板] 获取商品数据失败:', error);
    } finally {
      // no-op
    }
  }, []);
  
  
  
  // 计算总商品数
  const calculateTotalProducts = useMemo(() => {
    return products.length;
  }, [products]);
  
  // 从后端获取订单数据和商品数据
  // 使用 useRef 存储最新的函数引用，避免依赖项变化
  const fetchOrdersDataRef = React.useRef(fetchOrdersData);
  const fetchProductsRef = React.useRef(fetchProducts);
  const calculateRealTimeDataFromOrdersRef = React.useRef(calculateRealTimeDataFromOrders);
  
  // 更新 ref 的值（每次渲染时更新，确保使用最新函数）
  fetchOrdersDataRef.current = fetchOrdersData;
  fetchProductsRef.current = fetchProducts;
  calculateRealTimeDataFromOrdersRef.current = calculateRealTimeDataFromOrders;

  useEffect(() => {
    let isMounted = true; // 用于检查组件是否已卸载
    
    const fetchAllData = async () => {
      try {
        setLoading(true)
        // no product loading state

        // 添加超时处理，避免请求一直挂起（减少到3秒，提高响应速度）
        const timeoutPromise = new Promise((_, reject) => {
          setTimeout(() => reject(new Error('数据获取超时')), 3000); // 3秒超时
        });

        // 优化：先快速获取订单数据并显示，其他数据异步加载
        // 订单数据是最重要的，优先显示
        const ordersPromise = fetchOrdersDataRef.current().catch(err => {
          console.warn('[数据看板] 获取订单数据失败，使用模拟数据:', err);
          const mockOrders = generateMockOrders();
          if (isMounted) {
            setAllOrders(mockOrders);
            const realTimeStats = calculateRealTimeDataFromOrdersRef.current(mockOrders);
            setRealTimeData(prev => ({ ...prev, ...realTimeStats }));
          }
          return mockOrders;
        });

        // 订单数据获取后立即显示（不等待其他数据）
        const ordersResult = await Promise.race([ordersPromise, timeoutPromise]);
        
        // 如果订单数据已加载，先显示页面
        if (isMounted && ordersResult) {
          setLoading(false); // 先显示页面
        }

        // 其他数据异步加载（不阻塞页面显示）
        Promise.allSettled([
          fetchProductsRef.current().catch(err => {
            console.warn('[数据看板] 获取商品数据失败:', err);
            return null;
          })
        ]).catch(() => {
          // 静默失败，不影响页面显示
        });
      } catch (error) {
        console.error('获取看板数据失败:', error)
        // 即使失败也设置模拟数据，确保页面能显示
        if (isMounted) {
          const mockOrders = generateMockOrders();
          setAllOrders(mockOrders);
          const realTimeStats = calculateRealTimeDataFromOrdersRef.current(mockOrders);
          setRealTimeData(prev => ({ ...prev, ...realTimeStats }));
        }
      } finally {
        // 确保 loading 状态一定会被设置为 false（如果之前没有设置）
        if (isMounted) {
          setLoading(false)
        }
      }
    }
    
    fetchAllData()
    
    // 每5秒更新一次数据（不设置 loading 状态，避免影响页面显示）
    const interval = setInterval(() => {
      if (isMounted) {
        fetchOrdersDataRef.current().catch(err => {
          console.warn('[数据看板] 定时更新失败:', err);
        });
        fetchProductsRef.current().catch(err => {
          console.warn('[数据看板] 定时更新商品数据失败:', err);
        });
      }
    }, 5000)

    return () => {
      isMounted = false;
      clearInterval(interval);
    }
  }, []); // 空依赖数组，只在组件挂载时执行一次
  
  // 额外从后端仪表盘接口获取汇总指标、对比数据和业务模块数据
  useEffect(() => {
    let cancelled = false

    const fetchDashboardMeta = async () => {
      try {
        const [realResult, comparisonResult, businessResult] = await Promise.allSettled([
          dashboardAPI.getRealTimeData(),
          dashboardAPI.getComparison(),
          dashboardAPI.getBusinessModuleData()
        ])

        if (cancelled) return

        // 实时汇总指标：只覆盖后端能提供的字段，其余仍由订单数据计算
        if (realResult.status === 'fulfilled' && realResult.value) {
          const response = realResult.value as { data?: Partial<RealTimeData> }
          if (response.data) {
            setRealTimeData(prev => ({ ...prev, ...response.data }))
          }
        }

        // 数据对比分析：后端返回 current/previous 或 currentValue/previousValue，统一归一化
        if (comparisonResult.status === 'fulfilled' && comparisonResult.value) {
          const response = comparisonResult.value as { data?: unknown }
          const raw = response.data
          if (Array.isArray(raw)) {
            const normalized: DataComparisonItem[] = raw.map((item) => {
              const obj = item as {
                label?: string
                current?: number
                previous?: number
                currentValue?: number
                previousValue?: number
                unit?: string
              }
              const currentValue = obj.currentValue ?? obj.current ?? 0
              const previousValue = obj.previousValue ?? obj.previous ?? 0
              return {
                label: obj.label || '',
                currentValue,
                previousValue,
                unit: obj.unit || ''
              }
            })
            setComparisonData(normalized)
          }
        }

        // 业务模块占比数据
        if (businessResult.status === 'fulfilled' && businessResult.value) {
          const response = businessResult.value as { data?: BusinessModuleDataResponse }
          if (response.data) {
            setBusinessModuleData(response.data)
          }
        }
      } catch (error) {
        console.warn('[数据看板] 获取仪表盘扩展数据失败:', error)
      }
    }

    fetchDashboardMeta()

    return () => {
      cancelled = true
    }
  }, [])

  // 更新实时数据中的商品数量
  useEffect(() => {
    setRealTimeData(prev => ({
      ...prev,
      products: calculateTotalProducts
    }));
  }, [calculateTotalProducts]);

  // 从订单数据计算销售趋势（与销售统计页面保持一致）
  const calculatedSalesTrend = useMemo(() => {
    console.log('[数据看板] 开始计算销售趋势，订单数:', allOrders.length);
    const trendMap = new Map<string, { sales: number; orders: number }>();
    let processedCount = 0;
    let skippedCount = 0;

    allOrders.forEach((order: OrderData) => {
      try {
        if (!order.createdAt) {
          skippedCount++;
          return;
        }
        const orderDate = new Date(order.createdAt);
        if (isNaN(orderDate.getTime())) {
          skippedCount++;
          return;
        }
        // 统一使用 YYYY-MM-DD 格式
        const dateKey = orderDate.toISOString().split('T')[0];
        const price = parsePrice(order.totalPrice);
        if (!trendMap.has(dateKey)) {
          trendMap.set(dateKey, { sales: 0, orders: 0 });
        }
        const dayData = trendMap.get(dateKey)!;
        dayData.sales += price;
        dayData.orders += 1;
        processedCount++;
      } catch (e) {
        console.warn('[数据看板] 处理订单日期失败:', order._id, e);
        skippedCount++;
      }
    });

    const result = Array.from(trendMap.entries())
      .map(([date, data]) => ({
        date,
        sales: Math.round(data.sales),
        orders: data.orders
      }))
      .sort((a, b) => a.date.localeCompare(b.date));

    console.log('[数据看板] 销售趋势计算完成:', {
      处理订单数: processedCount,
      跳过订单数: skippedCount,
      趋势数据点数: result.length,
      趋势数据示例: result.slice(0, 3)
    });

    return result;
  }, [allOrders]);

  // 从订单数据计算类别销售（与销售统计页面保持一致）
  const calculatedCategorySales = useMemo(() => {
    console.log('[数据看板] 开始计算类别销售，订单数:', allOrders.length);
    const categoryMap = new Map<string, { sales: number; orders: number }>();
    let processedCount = 0;

    allOrders.forEach((order: OrderData) => {
      try {
        const productInfo = order.studentId;
        const categoryName = productInfo?.shopname || '未分类';
        const price = parsePrice(order.totalPrice);
        if (!categoryMap.has(categoryName)) {
          categoryMap.set(categoryName, { sales: 0, orders: 0 });
        }
        const categoryData = categoryMap.get(categoryName)!;
        categoryData.sales += price;
        categoryData.orders += 1;
        processedCount++;
      } catch (e) {
        console.warn('[数据看板] 处理订单类别失败:', order._id, e);
      }
    });

    const result = Array.from(categoryMap.entries())
      .map(([name, data]) => ({
        name,
        sales: Math.round(data.sales),
        orders: data.orders
      }))
      .sort((a, b) => b.sales - a.sales);

    console.log('[数据看板] 类别销售计算完成:', {
      处理订单数: processedCount,
      类别数量: result.length,
      类别数据示例: result.slice(0, 3)
    });

    return result;
  }, [allOrders]);

  // 从类别销售数据生成饼图数据（与销售统计页面保持一致）
  const calculatedSalesPie = useMemo(() => {
    if (calculatedCategorySales.length > 0) {
      const colors = ['#3b82f6', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#ec4899', '#06b6d4'];
      return calculatedCategorySales.map((item, index) => ({
        name: item.name,
        value: item.sales,
        color: colors[index % colors.length]
      }));
    }
    return [];
  }, [calculatedCategorySales]);

  // 合并数据源（优先使用计算的数据，与销售统计页面保持一致）
  const finalSalesTrendData = calculatedSalesTrend.length > 0 ? calculatedSalesTrend : salesTrendData;
  const finalCategorySalesData = calculatedCategorySales.length > 0 ? calculatedCategorySales : categorySalesData;
  const finalSalesPieData = calculatedSalesPie.length > 0 ? calculatedSalesPie : salesPieData;

  // 调试日志：检查数据状态
  useEffect(() => {
    console.log('[数据看板] 图表数据状态:', {
      订单总数: allOrders.length,
      计算趋势数据: calculatedSalesTrend.length,
      API趋势数据: salesTrendData.length,
      最终趋势数据: finalSalesTrendData.length,
      计算类别数据: calculatedCategorySales.length,
      API类别数据: categorySalesData.length,
      最终类别数据: finalCategorySalesData.length,
      计算饼图数据: calculatedSalesPie.length,
      API饼图数据: salesPieData.length,
      最终饼图数据: finalSalesPieData.length,
      趋势数据示例: finalSalesTrendData.slice(0, 3),
      类别数据示例: finalCategorySalesData.slice(0, 3),
      饼图数据示例: finalSalesPieData.slice(0, 3),
      订单数据示例: allOrders.slice(0, 3).map(o => ({
        id: o._id,
        date: o.createdAt,
        price: o.totalPrice,
        category: o.studentId?.shopname || '未知'
      }))
    });
  }, [allOrders, calculatedSalesTrend, salesTrendData, finalSalesTrendData,
  calculatedCategorySales, categorySalesData, finalCategorySalesData,
  calculatedSalesPie, salesPieData, finalSalesPieData]);

  // 计算关联数据 - 直接从订单数据计算，确保与订单管理页面完全同步
  const calculateTotalsFromOrders = useMemo(() => {
    let totalSales = 0;
    let totalOrders = 0;

    allOrders.forEach((order) => {
      try {
        const price = parsePrice(order.totalPrice);
        totalSales += price;
        totalOrders += 1;
      } catch (e) {
        console.warn('[数据看板] 处理订单价格失败:', order._id, e);
      }
    });

    return { totalSales, totalOrders };
  }, [allOrders]);

  // 从订单计算的总销售额和订单数
  const totalSalesFromOrders = calculateTotalsFromOrders.totalSales;
  const totalOrdersFromOrders = calculateTotalsFromOrders.totalOrders;
  
  // 4. 从数据对比中获取趋势百分比（用于实时数据卡片）
  const getTrendFromComparison = (label: string) => {
    const item = comparisonData.find(c => c.label.includes(label))
    if (item && item.previousValue > 0) {
      const change = ((item.currentValue - item.previousValue) / item.previousValue) * 100
      return {
        value: `${change > 0 ? '+' : ''}${change.toFixed(1)}%`,
        isUp: change > 0
      }
    }
    return null
  }
  // 5. 计算实时数据的趋势（基于数据对比）
  const salesTrend = getTrendFromComparison('销售额') || { value: '15.8%', isUp: true }
  const ordersTrend = getTrendFromComparison('订单数') || { value: '8.2%', isUp: true }
  const usersTrend = getTrendFromComparison('用户') || { value: '12.5%', isUp: true }

  // 获取筛选后的订单数据
  const getFilteredOrders = (dateRange: string = 'today', orderType: string = 'all') => {
    // 如果没有筛选日期，返回所有订单（从allOrders转换）
    if ((!filteredDate && dateRange === 'today') || allOrders.length === 0) {
      let ordersToConvert = [...allOrders];

      // 根据订单类型筛选
      if (orderType !== 'all') {
        switch (orderType) {
          case 'high-value':
            ordersToConvert = ordersToConvert.filter(order => parseFloat(order.totalPrice) >= 500);
            break;
          case 'pending':
            ordersToConvert = ordersToConvert.filter(order => order.status === '待处理');
            break;
          case 'completed':
            ordersToConvert = ordersToConvert.filter(order => order.status === '已完成');
            break;
          case 'recent':
            // 最近的10条订单
            ordersToConvert = [...ordersToConvert].sort((a, b) =>
              new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
            ).slice(0, 10);
            break;
          default:
            break;
        }
      }

      // 转换为OrderDetailModal需要的格式
      return ordersToConvert.slice(0, 15).map(order => ({
        id: order._id,
        product: order.studentId?.shopname || '未知商品',
        user: order.customerName || '未知用户',
        region: order.address?.split('市')[0] + '市' || '未知地区',
        amount: parseFloat(order.totalPrice) || 0,
        time: order.createdAt,
        status: order.status || '未知状态',
        store: order.studentId?.store || '未知店铺',
        quantity: order.quantity || 0,
        customerPhone: order.customerPhone || '未知电话',
        address: order.address || '未知地址'
      }));
    }

    // 根据筛选日期过滤订单
    const filtered = allOrders.filter(order => {
      const orderDate = new Date(order.createdAt).toLocaleDateString('zh-CN', {
        month: '2-digit',
        day: '2-digit'
      }).replace(/\//g, '-')
      return orderDate === filteredDate
    })

    // 转换为OrderDetailModal需要的格式，包含更多订单详情
    return filtered.map(order => ({
      id: order._id,
      product: order.studentId?.shopname || '未知商品',
      user: order.customerName || '未知用户',
      region: order.address?.split('市')[0] + '市' || '未知地区',
      amount: parseFloat(order.totalPrice) || 0,
      time: order.createdAt,
      status: order.status || '未知状态',
      store: order.studentId?.store || '未知店铺',
      quantity: order.quantity || 0,
      customerPhone: order.customerPhone || '未知电话',
      address: order.address || '未知地址'
    }))
  };

  // 查看订单明细，支持不同类型的订单筛选
  const handleViewOrders = useCallback((orderType: string = 'all', title?: string) => {
    setSelectedOrderType(orderType);
    setOrderDetailTitle(title || getOrderTypeTitle(orderType));
    setShowOrderDetail(true);
  }, []);

  // 根据订单类型获取标题
  const getOrderTypeTitle = (orderType: string): string => {
    switch (orderType) {
      case 'high-value':
        return '高价值订单明细';
      case 'pending':
        return '待处理订单明细';
      case 'completed':
        return '已完成订单明细';
      case 'recent':
        return '最新订单明细';
      default:
        return '今日订单明细';
    }
  };

  // 刷新订单数据 - 与销售统计页面同步的刷新逻辑
  const handleRefreshOrders = useCallback(() => {
    fetchOrdersData();
  }, [fetchOrdersData]);

  // 当订单数据变化时，重新计算实时销售数据，确保与销售统计页面同步
  // 注意：fetchOrdersData 中已经更新了实时数据，这里只作为备用更新
  // 使用 useMemo 来避免不必要的重复计算
  useEffect(() => {
    // 只在 allOrders 长度变化时更新，避免频繁刷新
    if (allOrders.length > 0) {
      const calculatedData = calculateRealTimeDataFromOrders(allOrders);
      setRealTimeData(prev => {
        // 只有当数据真正变化时才更新，避免无限循环
        const hasChanged = 
          prev.sales !== calculatedData.sales ||
          prev.orders !== calculatedData.orders ||
          prev.avgOrderValue !== calculatedData.avgOrderValue;
        
        if (hasChanged) {
          console.log('[数据看板] 订单数据变化，实时数据已更新');
          return { ...prev, ...calculatedData };
        }
        return prev;
      });
    }
  }, [allOrders, calculateRealTimeDataFromOrders]); // 包含 allOrders 以符合 ESLint 规则

  // 移除未使用的 realTimeCards 以避免 ESLint 未使用变量警告

  // 电商业务指标卡片数据（只显示与订单相关的数据）
  const statsData = [
    {
      title: '总销售额',
      icon: <DollarSign size={24} />,
      color: 'bg-blue-500',
      value: `¥${totalSalesFromOrders.toLocaleString()}`,
      trend: salesTrend
    },
    {
      title: '订单总数',
      icon: <ShoppingCart size={24} />,
      color: 'bg-green-500',
      value: totalOrdersFromOrders.toLocaleString(),
      trend: ordersTrend
    },

    {
      title: '注册用户',
      icon: <Users size={24} />,
      color: 'bg-purple-500',
      value: realTimeData.users.toLocaleString(),
      trend: usersTrend
    },
    {
      title: '商品总数',
      icon: <Package size={24} />,
      color: 'bg-orange-500',
      value: realTimeData.products.toLocaleString(),
      trend: { value: '5.3%', isUp: true }
    },
    {
      title: '转化率',
      icon: <Percent size={24} />,
      color: 'bg-pink-500',
      value: `${realTimeData.conversionRate}%`,
      trend: { value: '0.8%', isUp: true }
    },
    {
      title: '全量客单价',
      icon: <TrendingUp size={24} />,
      color: 'bg-indigo-500',
      value: `¥${realTimeData.avgOrderValue.toLocaleString()}`,
      trend: { value: '2.1%', isUp: true }
    },
    {
      title: '库存预警',
      icon: <AlertCircle size={24} />,
      color: 'bg-red-500',
      value: realTimeData.stockAlerts.toString(),
      trend: { value: '-5%', isUp: false }
    },
    {
      title: '退货率',
      icon: <Target size={24} />,
      color: 'bg-teal-500',
      value: `${realTimeData.returnRate}%`,
      trend: { value: '-0.5%', isUp: true }
    }
  ]

  // 趋势图数据 - 过去7天的数据
  const trendData = useMemo(() => {
    // 生成过去7天的日期数组
    const dates: string[] = []
    const today = new Date()
    today.setHours(0, 0, 0, 0) // 重置时间到当天0点
    for (let i = 6; i >= 0; i--) {
      const date = new Date(today)
      date.setDate(date.getDate() - i)
      dates.push(date.toISOString().split('T')[0])
    }

    console.log('[内容营销趋势] 生成的过去7天日期:', dates)
    console.log('[内容营销趋势] 订单总数:', allOrders.length)
    console.log('[内容营销趋势] 销售趋势数据:', finalSalesTrendData.length, '条')

    // 从订单数据中提取过去7天的销售数据
    const last7DaysData = new Map<string, number>()
    const sevenDaysAgo = new Date(today)
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 6)
    sevenDaysAgo.setHours(0, 0, 0, 0)

    let matchedOrdersCount = 0
    allOrders.forEach((order: OrderData) => {
      try {
        if (!order.createdAt) return
        const orderDate = new Date(order.createdAt)
        if (isNaN(orderDate.getTime())) return

        // 重置订单日期的时间部分，只比较日期
        orderDate.setHours(0, 0, 0, 0)

        // 只处理过去7天的订单
        if (orderDate >= sevenDaysAgo && orderDate <= today) {
          const dateKey = orderDate.toISOString().split('T')[0]
          const price = parsePrice(order.totalPrice)
          last7DaysData.set(dateKey, (last7DaysData.get(dateKey) || 0) + price)
          matchedOrdersCount++
        }
      } catch (e) {
        console.warn('[数据看板] 处理趋势图订单日期失败:', order._id, e)
      }
    })

    console.log('[内容营销趋势] 匹配的订单数:', matchedOrdersCount, '订单总数:', allOrders.length)
    console.log('[内容营销趋势] 从订单提取的数据:', Array.from(last7DaysData.entries()))

    // 如果过去7天没有订单数据，尝试使用所有订单数据（不限制7天）
    if (last7DaysData.size === 0 && allOrders.length > 0) {
      console.log('[内容营销趋势] 过去7天无订单，尝试使用所有订单数据')
      allOrders.forEach((order: OrderData) => {
        try {
          if (!order.createdAt) return
          const orderDate = new Date(order.createdAt)
          if (isNaN(orderDate.getTime())) return
          orderDate.setHours(0, 0, 0, 0)
          const dateKey = orderDate.toISOString().split('T')[0]
          // 只添加在日期范围内的数据
          if (dates.includes(dateKey)) {
            const price = parsePrice(order.totalPrice)
            last7DaysData.set(dateKey, (last7DaysData.get(dateKey) || 0) + price)
          }
        } catch (e) {
          console.warn('[数据看板] 处理所有订单数据失败:', order._id, e)
        }
      })
    }

    // 优先使用销售趋势数据（如果订单数据为空或不足）
    let useTrendData = false
    if (last7DaysData.size === 0 && finalSalesTrendData.length > 0) {
      useTrendData = true
      console.log('[内容营销趋势] 使用销售趋势数据作为数据源')
    }

    // 为每个日期生成值
    const values = dates.map(date => {
      // 首先尝试从订单数据获取
      let sales = last7DaysData.get(date) || 0

      // 如果订单数据为空，从销售趋势数据中获取
      if (sales === 0 && finalSalesTrendData.length > 0) {
        const trendItem = finalSalesTrendData.find(item => item.date === date)
        if (trendItem) {
          sales = trendItem.sales
          console.log('[内容营销趋势] 从销售趋势数据获取:', date, sales)
        }
      }

      // 如果还是没有数据，尝试获取销售趋势数据中最近的数据（即使日期不完全匹配）
      if (sales === 0 && finalSalesTrendData.length > 0 && useTrendData) {
        // 获取销售趋势数据中最近7天的数据
        const sortedTrend = [...finalSalesTrendData].sort((a, b) =>
          new Date(b.date).getTime() - new Date(a.date).getTime()
        )
        // 如果日期在范围内，使用对应的数据
        const trendItem = sortedTrend.find(item => {
          const itemDate = new Date(item.date)
          itemDate.setHours(0, 0, 0, 0)
          const targetDate = new Date(date)
          targetDate.setHours(0, 0, 0, 0)
          return itemDate.getTime() === targetDate.getTime()
        })
        if (trendItem) {
          sales = trendItem.sales
        }
      }

      return sales
    })

    console.log('[内容营销趋势] 最终生成的值:', values)

    // 计算总计
    const total = values.reduce((sum, val) => sum + val, 0)

    // 找到最高点作为高亮点
    const maxValue = values.length > 0 && values.some(v => v > 0)
      ? Math.max(...values.filter(v => v > 0))
      : 0
    const maxIndex = values.indexOf(maxValue)
    const highlightDate = maxIndex >= 0 ? dates[maxIndex] : dates[dates.length - 1]

    // 如果所有值都是0，使用销售趋势数据中最近7天的数据
    if (total === 0 && finalSalesTrendData.length > 0) {
      console.log('[内容营销趋势] 所有值都是0，尝试使用销售趋势数据中最近的数据')
      const sortedTrend = [...finalSalesTrendData].sort((a, b) =>
        new Date(b.date).getTime() - new Date(a.date).getTime()
      ).slice(0, 7).reverse() // 取最近7天，并反转顺序

      if (sortedTrend.length > 0 && sortedTrend.some(item => item.sales > 0)) {
        // 更新日期和值
        const newDates = sortedTrend.map(item => item.date)
        const newValues = sortedTrend.map(item => item.sales)
        const newTotal = newValues.reduce((sum, val) => sum + val, 0)
        const newMaxValue = newValues.length > 0 ? Math.max(...newValues) : 0
        const newMaxIndex = newValues.indexOf(newMaxValue)

        console.log('[内容营销趋势] 使用销售趋势数据:', newDates, newValues)

        return {
          dates: newDates.length >= 7 ? newDates.slice(0, 7) : [...newDates, ...dates.slice(newDates.length, 7)],
          values: newValues.length >= 7 ? newValues.slice(0, 7) : [...newValues, ...Array(7 - newValues.length).fill(0)],
    highlightPoint: {
            date: newMaxIndex >= 0 ? newDates[newMaxIndex] : dates[dates.length - 1],
            value: newMaxValue,
            label: `最高销售额: ¥${newMaxValue.toLocaleString()}`
          },
          total: newTotal
        }
      }
    }

    return {
      dates,
      values,
      highlightPoint: {
        date: highlightDate,
        value: maxValue,
        label: maxValue > 0 ? `最高销售额: ¥${maxValue.toLocaleString()}` : '暂无数据'
      },
      total
    }
  }, [allOrders, finalSalesTrendData])

  const defaultStoreTable = useMemo(() => ([
    { rank: 1, name: '北京市朝·首建金港商贸有限公司', visitors: '244.5w+', rate: '33%' },
    { rank: 2, name: '62126彰·西安彩虹商贸有限公司', visitors: '254.2w+', rate: '23%' },
    { rank: 3, name: '浙皖奶茶第一家·SWATCH本土工厂', visitors: '318.5w+', rate: '9%' },
    { rank: 4, name: '粤市医疗·制药门店金店新工坊', visitors: '357.9w+', rate: '17%' },
    { rank: 5, name: '人民的江·淘宝甲醛治理中心', visitors: '152.8w+', rate: '37%' }
  ]), [])

  // 根据商品数据生成线上热门门店列表，优先展示库存高的商品对应门店
  const tableData = useMemo(() => {
    if (!products || products.length === 0) {
      return defaultStoreTable
    }

    const sortedProducts = [...products].sort((a, b) => (b.nums || 0) - (a.nums || 0))

    return sortedProducts.slice(0, 5).map((product, index) => {
      const rank = index + 1
      const storeName = product.store ? `${product.store} · ${product.shopname}` : product.shopname
      const visitors = `${(Math.max(product.nums, 10) * 1.2 / 10).toFixed(1)}w+`
      const rateValue = Math.min(97, Math.max(3, Math.round((product.nums % 40) + 5)))

      return {
        rank,
        name: storeName,
        visitors,
        rate: `${rateValue}%`
      }
    })
  }, [products, defaultStoreTable])

  // 业务模块数据（从后端获取，如果没有则使用默认值）
  const businessModulePieData = businessModuleData?.data || [
    { name: '商品管理', value: 35, color: '#4F46E5' },
    { name: '订单管理', value: 25, color: '#06B6D4' },
    { name: '用户管理', value: 40, color: '#10B981' }
  ]

  // 如果数据还在加载，显示加载状态
  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-gray-500">加载中...</div>
      </div>
    )
  }

  return (
    <div className="space-y-6 animate-fade-in">
      {/* 页面标题区域 */}
      <div className="mb-6 animate-slide-up">
        <h2 className="text-2xl font-bold bg-gradient-to-r from-gray-800 via-gray-700 to-gray-800 bg-clip-text text-transparent mb-2">
          数据概览
        </h2>
        <p className="text-gray-500 text-sm">实时监控关键业务指标</p>
      </div>

      {/* 实时数据大屏 - 销售数据看板 */}
      <div className="bg-white rounded-lg shadow-sm border border-gray-100 p-4">
        <div className="flex items-center justify-between mb-4">
            <div>
            <h3 className="text-lg font-semibold text-gray-800 mb-1">实时数据</h3>
            <p className="text-gray-500 text-xs">实时监控销售数据</p>
            </div>
          <div className="flex items-center gap-3">
              <div className="flex items-center gap-2">
              <div className="w-2 h-2 bg-green-500 rounded-full"></div>
              <span className="text-xs text-gray-500">更新中</span>
              {lastSyncTime && (
                <span className="text-xs text-gray-400">
                  最后同步: {lastSyncTime}
                </span>
              )}
              </div>
              {/* 大屏模式切换按钮 */}
              <button
                onClick={() => setIsFullscreen(true)}
              className="flex items-center gap-1 px-3 py-1.5 text-xs text-gray-600 hover:text-gray-800 hover:bg-gray-50 rounded-md transition-colors"
              >
              <Maximize2 size={14} />
              <span>大屏</span>
              </button>
            </div>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          {/* 关联下方统计卡片的数据，确保数据一致性 */}
            <EnhancedMetricCard
              title="今日销售额"
              value={realTimeData.sales}
              unit="元"
              trend={{ 
              value: salesTrend?.value || '0%',
              isUp: salesTrend?.isUp !== undefined ? salesTrend.isUp : true
              }}
            previousValue={comparisonData.find(c => c.label.includes('销售额'))?.previousValue || realTimeData.sales - 1000}
            onClick={() => {
              handleViewOrders('all', '今日销售订单明细')
            }}
            />
            <EnhancedMetricCard
              title="今日订单数"
              value={realTimeData.orders}
              unit="单"
              trend={{ 
              value: ordersTrend?.value || '0%',
              isUp: ordersTrend?.isUp !== undefined ? ordersTrend.isUp : true
            }}
            previousValue={comparisonData.find(c => c.label.includes('订单数'))?.previousValue || realTimeData.orders - 5}
            onClick={() => {
              handleViewOrders('pending', '待处理订单明细')
            }}
            />
            <EnhancedMetricCard
              title="在线用户"
              value={realTimeData.users}
              unit="人"
              trend={{ value: 12.5, isUp: true }}
              previousValue={realTimeData.users - 10}
            />
            <EnhancedMetricCard
              title="商品总数"
              value={realTimeData.products}
              unit="件"
              trend={{ value: 5.3, isUp: true }}
              previousValue={realTimeData.products - 20}
            />
        </div>
      </div>
      
      {/* 大屏模式 */}
      <FullscreenMode isOpen={isFullscreen} onClose={() => setIsFullscreen(false)}>
        <div className="h-full w-full p-8">
          <div className="mb-8">
            <h1 className="text-5xl font-bold mb-2 bg-gradient-to-r from-white to-blue-200 bg-clip-text text-transparent">
              实时数据大屏
            </h1>
            <p className="text-xl text-blue-200">实时监控关键业务指标</p>
          </div>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <EnhancedMetricCard
              title="今日销售额"
              value={realTimeData.sales}
              unit="元"
              trend={{ 
                value: salesTrend?.value || '0%',
                isUp: salesTrend?.isUp !== undefined ? salesTrend.isUp : true
              }}
              previousValue={comparisonData.find(c => c.label.includes('销售额'))?.previousValue || realTimeData.sales - 1000}
              isFullscreen={true}
              onClick={() => {
                setFilteredDate('');
                setShowOrderDetail(true);
              }}
            />
            <EnhancedMetricCard
              title="今日订单数"
              value={realTimeData.orders}
              unit="单"
              trend={{ 
                value: ordersTrend?.value || '0%',
                isUp: ordersTrend?.isUp !== undefined ? ordersTrend.isUp : true
              }}
              previousValue={comparisonData.find(c => c.label.includes('订单数'))?.previousValue || realTimeData.orders - 5}
              isFullscreen={true}
              onClick={() => {
                setFilteredDate('')
                setShowOrderDetail(true)
              }}
            />
            <EnhancedMetricCard
              title="在线用户"
              value={realTimeData.users}
              unit="人"
              trend={{ value: 12.5, isUp: true }}
              previousValue={realTimeData.users - 10}
              isFullscreen={true}
            />
            <EnhancedMetricCard
              title="商品总数"
              value={realTimeData.products}
              unit="件"
              trend={{ value: 5.3, isUp: true }}
              previousValue={realTimeData.products - 20}
              isFullscreen={true}
            />
          </div>
          {/* 大屏模式下的图表 */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 border border-white/20">
              <h3 className="text-2xl font-bold mb-4 text-white">销售趋势</h3>
              <div className="h-64">
                {finalSalesTrendData.length > 0 ? (
              <AnimatedLineChart
                    data={finalSalesTrendData}
                lines={[
                  { dataKey: 'sales', name: '销售额', color: '#60a5fa', strokeWidth: 3 },
                ]}
                height={256}
                showAnimation={true}
              />
                ) : (
                  <div className="flex items-center justify-center h-64 text-white/60">
                    <div className="text-center">
                      <p className="text-sm">暂无数据</p>
                    </div>
                  </div>
            )}
              </div>
            </div>
            <div className="bg-white/10 backdrop-blur-sm rounded-2xl p-6 border border-white/20">
              <h3 className="text-2xl font-bold mb-4 text-white">销售占比</h3>
              <div className="h-64">
                {finalSalesPieData.length > 0 ? (
              <AnimatedPieChart
                    data={finalSalesPieData}
                height={256}
                showAnimation={true}
                innerRadius={60}
                outerRadius={100}
              />
                ) : (
                  <div className="flex items-center justify-center h-64 text-white/60">
                    <div className="text-center">
                      <p className="text-sm">暂无数据</p>
                    </div>
                  </div>
            )}
              </div>
            </div>
          </div>
        </div>
      </FullscreenMode>
      
      {/* 订单明细弹窗 - 增强版，显示更多订单详情 */}
      <OrderDetailModal
        isOpen={showOrderDetail}
        onClose={() => {
          setShowOrderDetail(false)
          setFilteredDate('') // 关闭时清除筛选条件
          setSelectedOrderType('all')
        }}
        orders={getFilteredOrders('today', selectedOrderType)}
        title={orderDetailTitle}
        showStatusFilter={true} // 显示状态筛选
        totalOrders={allOrders.length} // 显示总订单数
        refreshData={handleRefreshOrders}
      />

      {/* 门店详情弹窗 */}
      <StoreDetailModal
        isOpen={showStoreDetail}
        onClose={() => {
          setShowStoreDetail(false)
          setSelectedStore(null)
        }}
        store={selectedStore}
      />

      {/* 全部门店列表弹窗 */}
      <StoreListModal
        isOpen={showStoreList}
        onClose={() => setShowStoreList(false)}
        stores={tableData}
        onStoreClick={(store) => {
          setSelectedStore(store)
          setShowStoreList(false)
          setShowStoreDetail(true)
        }}
      />

      {/* 更多数据弹窗 */}
      <MoreDataModal
        isOpen={showMoreData}
        onClose={() => setShowMoreData(false)}
        stores={tableData}
      />

      {/* 原有统计卡片网格 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {statsData.map((stat, index) => (
          <StatsCard
            key={index}
            title={stat.title}
            icon={stat.icon}
            color={stat.color}
            value={stat.value}
            trend={stat.trend}
            delay={index * 100}
          />
        ))}
      </div>

      {/* 多维度图表区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 销售趋势折线图（带动画） */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-lg transition-shadow duration-300">
          <div className="p-6 bg-gradient-to-br from-white to-gray-50/50">
            <div className="flex items-center justify-between mb-6">
              <div>
                <h3 className="text-lg font-bold text-gray-800 mb-1">销售趋势分析</h3>
                <p className="text-xs text-gray-500">近30天销售数据变化（带动画效果）</p>
              </div>
              <div className="px-4 py-2 bg-blue-50 border border-blue-200 rounded-xl">
                <div className="text-xs text-gray-500 mb-1">30天总销售额</div>
                <div className="text-sm font-bold text-blue-600">
                  ¥{totalSalesFromOrders.toLocaleString()}
                </div>
                {realTimeData.sales > 0 && (
                  <div className="text-xs text-gray-400 mt-1">
                    今日占比: {((realTimeData.sales / totalSalesFromOrders) * 100).toFixed(2)}%
                  </div>
                )}
              </div>
            </div>
            <div className="relative">
              <AnimatedLineChart
                data={finalSalesTrendData}
                lines={[
                  { dataKey: 'sales', name: '销售额(元)', color: '#3b82f6', strokeWidth: 2 },
                  { dataKey: 'orders', name: '订单数(单)', color: '#10b981', strokeWidth: 2 },
                ]}
                height={300}
                showAnimation={finalSalesTrendData.length > 0}
              />
              {finalSalesTrendData.length === 0 && (
                <div className="absolute inset-0 flex items-center justify-center bg-white/90 backdrop-blur-sm pointer-events-none">
                  <div className="text-center">
                    <p className="text-sm text-gray-500 font-medium">暂无数据</p>
                    <p className="text-xs mt-1 text-gray-400">请等待数据加载或检查订单数据</p>
                    <p className="text-xs mt-1 text-gray-300">订单数: {allOrders.length}</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* 类别销售柱状图（带动画） */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-lg transition-shadow duration-300">
          <div className="p-6 bg-gradient-to-br from-white to-gray-50/50">
            <div className="flex items-center justify-between mb-6">
              <div>
                <h3 className="text-lg font-bold text-gray-800 mb-1">商品类别销售对比</h3>
                <p className="text-xs text-gray-500">各类别销售额与订单数对比（带动画效果）</p>
              </div>
              {totalSalesFromOrders > 0 && (
                <div className="px-4 py-2 bg-green-50 border border-green-200 rounded-xl">
                  <div className="text-xs text-gray-500 mb-1">类别总销售额</div>
                  <div className="text-sm font-bold text-green-600">
                    ¥{totalSalesFromOrders.toLocaleString()}
                  </div>
                  {realTimeData.sales > 0 && (
                    <div className="text-xs text-gray-400 mt-1">
                      今日: ¥{realTimeData.sales.toLocaleString()}
                    </div>
                  )}
                </div>
              )}
            </div>
            <div className="relative">
              <AnimatedBarChart
                data={finalCategorySalesData}
                bars={[
                  { dataKey: 'sales', name: '销售额(元)', color: '#3b82f6' },
                  { dataKey: 'orders', name: '订单数(单)', color: '#10b981' },
                ]}
                height={300}
                showAnimation={finalCategorySalesData.length > 0}
              />
              {finalCategorySalesData.length === 0 && (
                <div className="absolute inset-0 flex items-center justify-center bg-white/90 backdrop-blur-sm pointer-events-none">
                  <div className="text-center">
                    <p className="text-sm text-gray-500 font-medium">暂无数据</p>
                    <p className="text-xs mt-1 text-gray-400">请等待数据加载或检查订单数据</p>
                    <p className="text-xs mt-1 text-gray-300">订单数: {allOrders.length}</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 趋势图表 */}
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-lg transition-shadow duration-300 animate-slide-up" style={{ animationDelay: '300ms' }}>
        <div className="p-6 bg-gradient-to-br from-white to-gray-50/50">
          <div className="flex items-center justify-between mb-6">
            <div>
              <h3 className="text-lg font-bold text-gray-800 mb-1">内容营销趋势</h3>
              <p className="text-xs text-gray-500">过去7天的数据变化</p>
            </div>
            <div className="px-4 py-2 bg-blue-50 border border-blue-200 rounded-xl">
              <div className="text-xs text-gray-500 mb-1">总计</div>
              <div className="text-sm font-bold text-blue-600">
                {trendData.total ? `¥${trendData.total.toLocaleString()}` : '0'}
              </div>
            </div>
          </div>
          <TrendChart data={trendData} />
        </div>
      </div>

      {/* 数据对比分析区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {comparisonData.length > 0 && (
          <DataComparison title="数据对比分析" data={comparisonData} />
        )}
        
        {/* 销售占比饼图（带动画） */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-lg transition-shadow duration-300">
          <div className="p-6">
            <div className="mb-6">
              <div className="flex items-center justify-between mb-2">
                <div>
                  <h3 className="text-lg font-bold text-gray-800 mb-1">销售占比分析</h3>
                  <p className="text-xs text-gray-500">各商品类别销售占比（带动画效果）</p>
                </div>
                {totalSalesFromOrders > 0 && (
                  <div className="text-right">
                    <div className="text-xs text-gray-500">总销售额</div>
                    <div className="text-sm font-bold text-indigo-600">
                      ¥{totalSalesFromOrders.toLocaleString()}
                    </div>
                  </div>
                )}
              </div>
            </div>
            <div className="relative">
              <AnimatedPieChart
                data={finalSalesPieData}
                height={300}
                showAnimation={finalSalesPieData.length > 0}
                innerRadius={60}
                outerRadius={100}
              />
              {finalSalesPieData.length === 0 && (
                <div className="absolute inset-0 flex items-center justify-center bg-white/90 backdrop-blur-sm pointer-events-none">
                  <div className="text-center">
                    <p className="text-sm text-gray-500 font-medium">暂无数据</p>
                    <p className="text-xs mt-1 text-gray-400">请等待数据加载或检查订单数据</p>
                    <p className="text-xs mt-1 text-gray-300">订单数: {allOrders.length}</p>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 底部数据区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 数据表格 */}
        <div className="lg:col-span-2 animate-slide-up" style={{ animationDelay: '400ms' }}>
          <DataTable 
            title="线上热门门店"
            data={tableData}
            onRowClick={(row) => {
              setSelectedStore(row)
              setShowStoreDetail(true)
            }}
            onViewAll={() => {
              setShowStoreList(true)
            }}
            onMoreData={() => {
              setShowMoreData(true)
            }}
          />
        </div>

        {/* 业务模块数据占比 */}
        <div className="animate-slide-up" style={{ animationDelay: '500ms' }}>
          <PieChartCard 
            title="业务模块使用占比"
            data={businessModulePieData}
            monthOnMonth={businessModuleData?.monthOnMonth}
            yearOnYear={businessModuleData?.yearOnYear}
          />
        </div>
      </div>
    </div>
  )
}

export default Dashboard;
